let isProductUpdateAndDeleteTab = true;
let isProductOtherTab = true;

layui.use('treetable', function() {
    var datas = []//页面左边的产品目录数据
    var treetables = layui.treetable,
        layer = layui.layer,
        table = layui.table,
        $ = layui.jquery,
        upload=layui.upload,
        form=layui.form,
        isProductAdmin = false,
        re = "",
        fileid="0";//左边目录点击选中的id
    var cataCode="",//右边选中的目录编号
        cataCodeName="",
        selectdata=[];//右边查询条件中的目录数据
    var cataCodeList="";//右边选中目录的 下级目录code集合

    query();
    queryPid();
    getLoginUserInfo();

    var catalogAll=queryAll();
    var hs=getdictionary(3,8);//海关

    //目录树
    let productTreeList=[];

    //判断当前用户是否是：研发主管、研发助理、管理员、财务、产品交付中心、品质经理
    function getIsProductAdmin() {
        $.ajax({
            url: 'customer/isProductAdmin',
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    isProductAdmin = da.data;
                }
            }
        });
    }

    layer.ready(function () {
        //判断当前用户是否是：研发主管、研发助理、管理员、财务、产品交付中心、品质经理
        getIsProductAdmin();
        if(isProductAdmin){
            $(".Authority-Label").show();
        }
        //订单操作标签 有该标签:false 无该标签:true
        isProductUpdateAndDeleteTab = getAllRolesByCurr("ProductUpdateAndDeleteTab");
        //产品其它标签 有该标签:false 无该标签:true
        isProductOtherTab = getAllRolesByCurr("ProductOtherTab");
        //产品目录
        let treeList=toTree(selectdata);
        if(treeList){
            let productTree = getAllJson(treeList);
            productTreeList=getxmselect("#directory","cataCode", productTree)
        }else {
            productTreeList=getxmselect("#directory","cataCode", [])
        }

        cataCode=productTreeList.getValue('valueStr');
    })




    getCatalogBycode(cataCode);
    form.render();
    form.render('select');

    // 渲染表格
    re = treetables.render({
        elem: '#producttree',
        data: datas,
        toolbar:"#producttreetoolbar",
        id:"producttreeid",
        tree: {
            iconIndex: 1,           // 折叠图标显示在第几列
            isPidData: false,        // 是否是id、pid形式数据
            idName: 'fileid',  // id字段名称
        },
        page: false,
        //treeLinkage: true,      //父级展开时是否自动展开所有子级
        cols: [[
            {type:"checkbox", fixed: true},
            {title: "产品目录", field: "name", fixed: true},
            {title: "操作", templet: "#producttreeeditor",width:120, align:'center'}
        ]],
        height:$(document).height() - $('#producttree').offset().top - 130+""//字符串类型的高度
    })

    //取所有目录（列表格式）只有code和name，用于表格中产品目录匹配
    function queryAll() {
       var catalogAll=[];
        $.ajax({
            type : 'get',
            url:'productcatalog/queryAll',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                  for(var i=0;i<da.data.length;i++){
                        var obj={};
                        obj.code=da.data[i].code;
                        obj.name=da.data[i].name;
                      catalogAll.push(obj);
                  }

                }
            }
        });
       return catalogAll;
    }

    //获取所有产品目录json集合，页面左边的产品目录数据
    function query(){
        $.ajax({
            type : 'get',
            url:'productcatalog/select',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    datas=getdatas(da.data.children);
                }
            }
        });
    }

    //json转换树，并重新定义字段
    function getdatas(da){
        var objs=[];
        for(var i=0;i<da.length;i++){
            var obj={};
            obj.fileid=da[i].id;
            obj.name=da[i].name;
            obj.type="";
            obj.parentId=da[i].pid;
            obj.path=da[i].path;
            obj.remark=da[i].remark;
            obj.code=da[i].code
            if(da[i].children.length !=0 ){
                obj.children=getdatas(da[i].children);
            }
            objs.push(obj);
        }
        return objs;
    }
    //左边目录树 搜索
    $('#search').click(function () {
        re.filterData($("#treename").val());
    });
    //  左边树监听行单击事件
    treetables.on('row(producttree)', function(obj){
        cataCode=obj.data.code;
        cataCodeName=obj.data.name;
        window.sessionStorage.setItem("cataCodeMo",cataCode);
        window.sessionStorage.setItem("cataId",obj.data.fileid);

        //设置右边目录选中该值
        productTreeList.setValue([ cataCode ]);
        form.render();

        //设置左边树的样式
        var selecteds = $(".selecteds");
        if(typeof (selecteds[0])!="undefined"){
            selecteds.removeClass("selecteds");
        }
        obj.tr[0].classList.add("selecteds");
        re.expand(obj.data.fileid);  // 展开指定节点
        $('#productttype').val(obj.data.name);
        fileid = obj.data.fileid;

        // getCatalogBycode(obj.data.code);

        //刷新产品表格
        table.reload('producttableid', {
            type:"get"
            ,url:"productmaininfo/selectByPage"
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where: {
                "cataCode": obj.data.code,
                "code":"",
                "chinaName":"",
                "englishName":"",
                "gecode":"",
                "ge":"",
                "upCataCodePath":"",
            }
        }, 'data');
       // console.log(obj.data) //得到当前行数据
    });

    //树添加、删除
    treetables.on('toolbar(producttree)', function (obj) {
        var checkStatus = re.checkStatus(false);  // 获取选中数据，不要半选状态

        switch (obj.event) {
            case 'newuser':
               /* if(checkStatus.length==0){
                    layer.msg("请选择将要添加的父目录");
                }else if(checkStatus.length >1){
                    layer.msg("只能选择一个父目录");
                }else if((checkStatus[0].path+"/").startsWith("/0/3/") || (checkStatus[0].path+"/").startsWith("/0/4/")){
                    layer.msg("垃圾箱和回收箱不能作为父目录");
                }else{*/
                    parent.intab("views/jsp/BasicData/tpl/newupdirectory.jsp","新增目录")
               // }

                break;
            case 'deluser':
                var ids=[];
                if(checkStatus.length==0){
                    layer.msg("请选择要删除的节点", {icon: 6});
                    break;
                }
                for(var i=0;i<checkStatus.length;i++){
                    ids.push(checkStatus[i].fileid);
                }
                if(deltree(ids)){
                    layer.msg("删除成功", {icon: 6});
                    refrash();
                }else{
                    layer.msg("删除失败", {icon: 6});
                }
                break;
        }
    });
//树行中修改、删除
    treetables.on('tool(producttree)', function(obj){
        var data = obj.data;  // 获得当前行数据
        var event = obj.event; // 获得lay-event对应的值
        if(event === 'editor') {
            window.sessionStorage.setItem("productMidifyData",JSON.stringify(data));
            parent.intab("views/jsp/BasicData/tpl/newupdirectory.jsp?id="+data.fileid,"修改目录")
        }else if (event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                if(delpaths(data.path)){
                    obj.del(); // 删除对应行，并更新缓存
                    layer.msg("删除成功", {icon: 6});
                }else{
                    layer.msg("删除失败", {icon: 6});
                }

                layer.close(index);
            });
        }
    });



    //垫片
    //垫片种类编码设置
    $("#gasketTypeCodeSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/gasketTypeCodeSetting.jsp","垫片种类编码设置")
    });

    //垫片种类设置
    $("#gasketTypeSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/gasketTypeSetting.jsp","垫片种类设置")
    });

    //垫片耳朵设置
    $("#spacerEarSettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/spacerEarSettings.jsp","垫片耳朵设置")
    });

    //垫片特殊参数设置
    $("#gasketParameterSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/gasketParameterSetting.jsp","垫片特殊参数设置")
    });

    //垫片尺寸设置
    $("#gasketSizeSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/gasketSizeSetting.jsp","垫片尺寸设置")
    });

    //印刷稿件简码设置
    $("#manuscriptCodeSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/manuscriptCodeSetting.jsp","印刷稿件简码设置")
    });

    //特殊需求设置
    $("#gasketSpecialNeedsSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/gasketSpecialNeedsSetting.jsp","特殊需求(垫片)设置")
    });



    //其它
    //其它:规格尺寸设置
    $("#otherSpecificationSizeSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/otherSpecificationSizeSetting.jsp","规格尺寸设置")
    });

    //其它:特殊参数设置
    $("#otherSpecialParametersSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/otherSpecialParametersSetting.jsp","特殊参数设置")
    });

    //其它:品类设置(其它)
    $("#otherCategorySetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/otherCategorySetting.jsp","品类设置(其它)")
    });

    //其它:客户货号设置
    $("#otherCustomerNumberSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/otherCustomerNumberSetting.jsp","客户货号设置")
    });

    //其它:特殊需求设置
    $("#otherSpecialNeedsSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/otherSpecialNeedsSetting.jsp","特殊需求(其它)设置")
    });


    //配件
    //种类设置
    $("#partsCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsCategorySettings.jsp","种类设置")
    });

    //模具类别设置
    $("#partsMoldCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsMoldCategorySettings.jsp","模具类别设置")
    });

    //品类设置
    $("#partsFirstCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsFirstCategorySettings.jsp","品类设置")
    });

    //规格设置
    $("#partsSecondaryCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsSecondaryCategorySettings.jsp","规格设置")
    });

    //材质设置
    $("#partsThreeCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsThreeCategorySettings.jsp","材质设置")
    });

    //工艺设置
    $("#partsCraftSettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsCraftSettings.jsp","工艺设置")
    });

    //颜色订货号设置
    $("#partsColorOrderNumberSettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsColorOrderNumberSettings.jsp","颜色订货号设置")
    });

    //私模订货号设置
    $("#partsPrivateMoldNumberSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsPrivateMoldNumberSetting.jsp","私模订货号设置")
    });

    //特殊需求设置
    $("#partsSpecialNeedsSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/partsSpecialNeedsSetting.jsp","特殊需求(配件)设置")
    });


    //包材
    //种类设置
    $("#categorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/categorySettings.jsp","种类设置")
    });

    //模具类别设置
    $("#moldCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/moldCategorySettings.jsp","模具类别设置")
    });

    //品类设置
    $("#firstCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/firstCategorySettings.jsp","品类设置")
    });

    //规格设置
    $("#secondaryCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/secondaryCategorySettings.jsp","规格设置")
    });

    //材质设置
    $("#threeCategorySettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/threeCategorySettings.jsp","材质设置")
    });

    //工艺设置
    $("#craftSettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/craftSettings.jsp","工艺设置")
    });

    //颜色订货号设置
    $("#colorOrderNumberSettings").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/colorOrderNumberSettings.jsp","颜色订货号设置")
    });

    //私模订货号设置
    $("#privateMoldNumberSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/privateMoldNumberSetting.jsp","私模订货号设置")
    });

    //特殊需求设置
    $("#specialNeedsSetting").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/specialNeedsSetting.jsp","特殊需求(包材)设置")
    });


//海关编码
    $("#customscode").on('click',function () {
        parent.intab("views/jsp/SystemCenter/tpl/HScode.jsp","海关编码设置")
    });

    layui.use(['dropdown'], function () {
        let dropdown = layui.dropdown;
        dropdown.onFilter("statistics", function (event) {
            switch (event) {
                case "s1":
                    parent.intab("views/jsp/BasicData/tpl/productDetailStatistics.jsp", "产品创建日期及修改日期统计")
                    break
                case "s2":
                    parent.intab("views/jsp/BasicData/tpl/productGroupDetailStatistics.jsp", "按供应商采购产品情况统计")
                    break
                case "s3":
                    parent.intab("views/jsp/BasicData/tpl/productPriceDetailStatistics.jsp", "厂商产品排价")
                    break
                case "s4":
                    parent.intab("views/jsp/BasicData/tpl/productPurchaseTopStatistics.jsp", "产品采购Top")
                    break
                case "s5":
                    parent.intab("views/jsp/BasicData/tpl/productNotEnteredPurchaseStatistics.jsp", "产品未录入单价下采购单统计")
                    break
            }
        });
    })



    //产品表格
    table.render({
        elem: '#productid'
        ,type:"get"
        ,url:"productmaininfo/selectByPage"
        ,where:{
            "cataCode":cataCode
        }
        , toolbar: '#producttoolbar'
        , cols: [[
            {type:"checkbox", fixed: true}
            ,{field: 'img', title: '图片', width: 120, align: 'center', templet: '#imgTpl',event:'img' },
            {field: 'code', width: 120, title: '产品编码', sort: true,event: 'eventCode'},
            {field: 'gecode', width: 310, title: '规格编码', sort: true,event: 'eventCode'},
            {field: 'chinaRemark', width: 310, title: '中文描述', sort: true,event: 'eventCode'},
            {field: 'chinaName', width: 120, title: '中文名称', sort: true,event: 'eventCode'},
            {field: 'englishName', width: 120, title: '英文名称', sort: true,event: 'eventCode'},
            {field: 'bzsm', width: 120, title: '规格说明', sort: true,event: 'eventCode'},
            {field: 'unit', width: 120, title: '单位', sort: true,event: 'eventCode'},
            {field: 'hgCode', width: 120, title: '海关编码', sort: true,event: 'eventCode'},
            {field:'taxRate', title:'退税率',  width: 120,sort: true,event: 'eventCode'},
            {field:'importTariff', title:'关税税率', width: 120, sort: true,event: 'eventCode'},
            {field: 'cataCode', width: 120, title: '所属目录', sort: true,event: 'eventCode'},
            {field: 'deactivateTypeStr', width: 120, title: '是否停用', sort: true},
            {fixed: 'right', width: 180, align: 'center', toolbar: '#producteditor', title: '操作'}
        ]]
        , id: 'producttableid'
        , height: $(document).height() - $('#productid').offset().top - 50
        , page: true
        , limit: 100
        ,limits:[100,200,300,400,500,600,700,800,900,1000]
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            hoverOpenImg();//显示大图
            $("[data-field = 'cataCode']").children().each(function(){

               /* for(var i=0;i<dw.length;i++){
                    if($(this).text()==dw[i].code){
                        $(this).text(dw[i].name);
                    }
                }*/
                //catalogAll
                for(var i=0;i<catalogAll.length;i++){
                    if($(this).text()==catalogAll[i].code){
                        $(this).text(catalogAll[i].name);
                    }
                }
            })
            $("[data-field = 'hgCode']").children().each(function(){

                /* for(var i=0;i<dw.length;i++){
                     if($(this).text()==dw[i].code){
                         $(this).text(dw[i].name);
                     }
                 }*/
                //catalogAll
                for(var i=0;i<hs.length;i++){
                    if($(this).text()==hs[i].code){
                        $(this).text(hs[i].name);
                    }
                }
            })


        }
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    function queryNameBycode(code){

        for(var i=0;i<selectdata.length;i++){
            if(code==selectdata[i].code) return selectdata[i].name
        }
        return "";
    }
    //监听提交搜索
    form.on('submit(form-search)', function (data) {
        cataCode=data.field.cataCode;
        cataCodeName=queryNameBycode(cataCode);//selectdata[0].name;

        // getCatalogBycode(data.field.cataCode);
        table.reload('producttableid', {
            type:"get"
            ,url:"productmaininfo/selectByPage"
            ,page: {
                curr: 1, //重新从第 1 页开始
                limit: 100
            }
            ,where: {
                "cataCode": data.field.cataCode,
                "code":data.field.code,
                "chinaName":data.field.chinaName,
                "englishName":data.field.englishName,
                "gecode":data.field.gecode,
                "ge":data.field.ge,
                "upCataCodePath":"",
                "chineseDesc":data.field.chineseDesc,
                "englishDesc":data.field.englishDesc,
            }
        }, 'data');
        return false;
    });

    //工具栏
    table.on('toolbar(producttable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        let data = checkStatus.data;
        switch (obj.event) {
            //新增产品--选配件
            case 'newuser':
                if(cataCode ==""){
                    layer.msg("请选择产品目录");
                    return false;
                }
                window.sessionStorage.setItem("cataCodeName",JSON.stringify(cataCodeName));
                window.sessionStorage.setItem("cataCode",JSON.stringify(cataCode));
                window.sessionStorage.setItem("code","");
                parent.intab("views/jsp/BasicData/tpl/newupproduct.jsp","新增产品")
                break;
            //包材
            case 'productNotParts':
                if(cataCode ==""){
                    layer.msg("请选择产品目录");
                    return false;
                }
                window.sessionStorage.setItem("cataCodeName",JSON.stringify(cataCodeName));
                window.sessionStorage.setItem("cataCode",JSON.stringify(cataCode));
                window.sessionStorage.setItem("code","");
                parent.intab("views/jsp/BasicData/tpl/productNotParts.jsp","新增包材")
                break;
            //其它
            case 'newOtherProduct':
                if(cataCode ==""){
                    layer.msg("请选择产品目录");
                    return false;
                }
                window.sessionStorage.setItem("cataCodeName",JSON.stringify(cataCodeName));
                window.sessionStorage.setItem("cataCode",JSON.stringify(cataCode));
                window.sessionStorage.setItem("code","");
                parent.intab("views/jsp/BasicData/tpl/newOtherProduct.jsp","新增其它")
                break;
            //垫片
            case 'newParts':
                if(cataCode ==""){
                    layer.msg("请选择配件目录");
                    return false;
                }
                window.sessionStorage.setItem("cataCodeName",JSON.stringify(cataCodeName));
                window.sessionStorage.setItem("cataCode",JSON.stringify(cataCode));
                window.sessionStorage.setItem("code","");
                parent.intab("views/jsp/BasicData/tpl/newParts.jsp","新增配件")
                break;
            //产品合并
            case 'newProductAndParts':
                if(cataCode ==""){
                    layer.msg("请选择产品目录");
                    return false;
                }
                window.sessionStorage.setItem("cataCodeName",JSON.stringify(cataCodeName));
                window.sessionStorage.setItem("cataCode",JSON.stringify(cataCode));
                window.sessionStorage.setItem("code","");
                parent.intab("views/jsp/BasicData/tpl/newProductAndParts.jsp","产品合并")
                break;
            case 'restorefile':
                if(data.length!=0){
                    layer.confirm('真的恢复选中文件么', function (index) {
                        var delid = [];
                        for (var i = 0;i<data.length;i++){
                            delid.push(data[i].id)
                        }
                        if(hf(delid)){
                            layer.msg("恢复成功");
                            layer.close(index);
                            refrash();
                        }else{
                            layer.msg("恢复失败");
                        }
                       // layer.msg('需要恢复的数据ID为：'+ JSON.stringify(delid) + ',执行恢复');
                        // layer.msg("恢复成功", {icon: 6});
                      /*  layer.close(index);
                        table.reload('producttableid', {where: {
                                fileid: fileid
                        }}); //ajax恢复成功之后刷新表格*/
                    });
                }else{
                    layer.msg("请选择要恢复的文件");
                }
                 break;
            case 'deluser'://删除
                if(data.length!=0){
                    var delid = [];
                    for (var i = 0;i<data.length;i++){
                        delid.push(data[i].id)
                    }
                    if(delproduct(delid)){
                        layer.msg("删除成功");
                        refrash();
                    }else{
                        layer.msg("删除失败");
                    }
                   /* layer.msg('需要删除的数据ID为：'+ JSON.stringify(delid) + ',执行删除');
                    table.reload('producttableid',{where: {
                        fileid: fileid
                    }});*/ //ajax删除成功之后刷新表格
                }else{
                    layer.msg("请选择要删除的数据");
                }
                break;
            case 'uploadFile':
                parent.intab("views/jsp/BasicData/fileUpload.jsp?model=product","文件上传")
                break;
            case 'deactivate':
                if(data.length!=0){
                    let ids = [];
                    let codes=[];
                    for (var i = 0;i<data.length;i++){
                        ids.push(data[i].id);
                        codes.push(data[i].code)
                    }
                    deactivate(ids,codes);
                }else{
                    layer.msg("请选择要停用的数据");
                }
                break;
        }
    });
    var rowflag=0;
    // table.on('tool(producttable)', function (obj) {
    //     var data=obj.data;
    //
    //     if(rowflag=="0"){
    //         window.sessionStorage.setItem("cataCodeName",JSON.stringify(cataCodeName));
    //         window.sessionStorage.setItem("cataCode",JSON.stringify(cataCode));
    //         parent.intab("views/jsp/BasicData/tpl/viewproduct.jsp?id="+data.id,"查看产品详情");
    //     }else{
    //         rowflag=0;
    //     }
    //
    // });
    table.on('tool(producttable)', function (obj) {
        rowflag=1;
        let data = obj.data;
        //产品编码
        let productCode = data["code"];
        //规格编码
        let specNo = data["gecode"];
        if(obj.event === 'editor'){
            for (var i = 0; i < selectdata.length; i++){
                if(data.cataCode==selectdata[i].id){
                    window.sessionStorage.setItem("cataCodeName",JSON.stringify(selectdata[i].name));
                }
            }
            window.sessionStorage.setItem("cataCode",JSON.stringify(data.cataCode));
            window.sessionStorage.setItem("code",JSON.stringify(data.code));
            //校验数据是否被调用
            $.ajax({
                url: "carryDetail/checkProductIsUsed?productCode=" + productCode + "&specNo=" +specNo,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        let msg = "";
                        if (1 === res.data) {
                            msg = "已做外销，只能修改供应商信息，是否继续？";
                        } else if (2 === res.data) {
                            msg = "已做备货，只能修改供应商信息，是否继续？";
                        } else if (3 === res.data) {
                            msg = "已做采购，只能修改供应商信息，是否继续？";
                        } else if (4 === res.data) {
                            msg = "已做库存，只能修改供应商信息，是否继续？";
                        }
                        if (isEmpty(msg)) {
                            let productType = data.productType;
                            switch (productType) {
                                case 1:
                                    //包材不可选配件
                                    parent.intab("views/jsp/BasicData/tpl/productNotParts.jsp?id=" + data.id + "&isUsed=" + res.data, "修改包材");
                                    break;
                                case 2:
                                    //垫片-配件
                                    parent.intab("views/jsp/BasicData/tpl/newParts.jsp?id=" + data.id + "&isUsed=" + res.data, "修改配件");
                                    break;
                                case 3:
                                    //包材可选配件
                                    parent.intab("views/jsp/BasicData/tpl/newupproduct.jsp?id=" + data.id + "&isUsed=" + res.data, "修改产品");
                                    break;
                                case 4:
                                    //其它
                                    parent.intab("views/jsp/BasicData/tpl/newOtherProduct.jsp?id=" + data.id + "&isUsed=" + res.data, "修改其它");
                                    break;
                            }
                        } else {
                            layer.confirm(msg, confirmInfo(3, 6), function (index) {
                                parent.intab("views/jsp/BasicData/tpl/newupproduct.jsp?id=" + data.id + "&isUsed=" + res.data, "修改产品");
                                layer.close(index);
                                return;
                            })
                        }

                    } else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        }else if (obj.event === 'del') {
            //校验数据是否被调用
            $.ajax({
                url: "carryDetail/checkProductIsUsed?productCode=" + productCode + "&specNo=" + specNo,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        let msg = "";
                        if (1 === res.data) {
                            msg = "已做外销，是否删除？";
                        } else if (2 === res.data) {
                            msg = "已做备货，是否删除？";
                        } else if (3 === res.data) {
                            msg = "已做采购，是否删除？";
                        } else if (4 === res.data) {
                            msg = "已做库存，是否删除？";
                        }
                        if (isEmpty(msg)) {
                            layer.confirm("确认删除？", confirmInfo(3, 6), function (index) {
                                let delid = [];
                                delid.push(data.id);
                                if(delproduct(delid)){
                                    layer.msg("删除成功");
                                    refrash();
                                }else{
                                    layer.msg("删除失败");
                                }
                            })
                        }else {
                            layer.confirm(msg, confirmInfo(3, 6), function (index) {
                                let delid = [];
                                delid.push(data.id);
                                if(delproduct(delid)){
                                    layer.msg("删除成功");
                                    refrash();
                                }else{
                                    layer.msg("删除失败");
                                }
                                return;
                            })
                        }
                    }
                }
            });
        }else if(obj.event === 'img'){//obj.event === 'productcode'

            return false;
        }else if(obj.event === 'eventCode'){
            let productType = data.productType;
            switch (productType) {
                case 2:
                    //查看配件详情
                    window.sessionStorage.setItem("cataCodeName", JSON.stringify(cataCodeName));
                    window.sessionStorage.setItem("cataCode", JSON.stringify(cataCode));
                    parent.intab("views/jsp/BasicData/tpl/viewProductParts.jsp?id=" + data.id, "查看配件详情");
                    break;
                case 4:
                    window.sessionStorage.setItem("cataCodeName", JSON.stringify(cataCodeName));
                    window.sessionStorage.setItem("cataCode", JSON.stringify(cataCode));
                    parent.intab("views/jsp/BasicData/tpl/viewOtherProduct.jsp?id=" + data.id, "查看其它详情");
                    break;
                default:
                    window.sessionStorage.setItem("cataCodeName", JSON.stringify(cataCodeName));
                    window.sessionStorage.setItem("cataCode", JSON.stringify(cataCode));
                    parent.intab("views/jsp/BasicData/tpl/viewproduct.jsp?id=" + data.id, "查看产品详情");

            }
            return false;

        }

    });
    //树添加删除
    function deltree(ids) {
        var tf=false;
        $.ajax({
            type : 'post',
            data:{"ids":JSON.stringify(ids)},
            url:'productcatalog/delete',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                   tf=da.data==0?false:true;
                }
            }
        });
        return tf;
    }

    //根据path删除
    function  delpaths(path) {
        var tf=false;
        $.ajax({
            type : 'post',
            data:{"path":path},
            url:'productcatalog/deleteByPath',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    tf=da.data==0?false:true;
                }
            }
        });
        return tf;
    }

    function refrash() {
        // getCatalogBycode(productTreeList.getValue('valueStr'));
        table.reload('producttableid', {
            type:"get"
            ,url:"productmaininfo/selectByPage"
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where: {
                "cataCode": productTreeList.getValue('valueStr'),
                "code":$("input[name='code']")[0].value,
                "chinaName":$("input[name='chinaName']")[0].value,
                "englishName":$("input[name='englishName']")[0].value,
                "gecode":$("input[name='gecode']")[0].value,
                "ge":$("input[name='ge']")[0].value
            }
        }, 'data');
    }

    //获取产品目录信息,右边查询条件中的目录数据 按理说应该和左边的目录一样
    function queryPid() {
        $.ajax({
            type : 'get',
            url:'productcatalog/getProductDirectoryInfo',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    selectdata=da.data;
                }
            }
        });
    }

    //根据主键删除产品
    function  delproduct(ids) {
        var tf=false;
        $.ajax({
            type : 'post',
            data:{"ids":JSON.stringify(ids)},
            url:'productmaininfo/delproduct',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                   tf= da.data >0 ;
                }
            }
        });
        return tf;
    }
    //恢复
    function  hf(ids) {
        var tf=false;
        $.ajax({
            type : 'post',
            data:{"ids":JSON.stringify(ids)},
            url:'productmaininfo/hf',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    tf= da.data >0 ;
                }
            }
        });
        return tf;
    }

    /**
     * 根据产品目录 code获取其下级所有的code
     */
    function getCatalogBycode(code){
        $.ajax({
            type : 'get',
            data:{"code":code},
            url:'productmaininfo/getCatalogBycode',
            dataType:"json",
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    cataCodeList=JSON.stringify(da.data);
                }
            }
        });
    }


    //控制 按厂商产品分组详情 显示或隐藏
    function getLoginUserInfo() {
        let user;
        //获取当前登陆用户名称
        $.ajax({
            url:"productmaininfo/getLoginUserInfo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    user=data.data;
                }
            }
        });
        let currentBtn1 = document.getElementById("titlerightone");
        let currentBtn2 = document.getElementById("titlerighttwo");
        let currentBtn3 = document.getElementById("titlerighThree");
        if (user.code == "RKB004" || user.code == "RKB024" || user.code == "RKB066" || user.code == "RKB080" || user.code == "RKB004" || user.code == "admin" || user.code == "RKB006" || user.code == "RKB003") {
            currentBtn1.style.display = "block"; //style中的display属性
        }else if (user.code == "RKB007" ||user.code == "RKB037" ||user.code == "RKB068"){
            currentBtn3.style.display = "block";
        }else{
            currentBtn2.style.display = "block";
        }
    }


    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }



    //停用
    function deactivate(ids,codes) {
        $.ajax({
            url:"productmaininfo/deactivateProduct?ids="+ids+"&codes="+codes,
            async:false,
            success:function(data){
                if(data.status == 200){
                    layer.msg("停用"+data.data+"款产品成功");
                    refrash();
                }else if (data.status == -301){
                    // layer.msg("其中产品已在库存中存在！不能停用");
                    layer.msg(data.msg, {icon: 5});
                }else {
                    layer.msg("停用失败");
                }
            },
            error:function (data) {
                layer.msg("停用失败");
            }
        });
    }


    function getAllJson(jsons) {
        let tmpitem=[]
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            if(item["children"]){
                tmparr["children"]=  getAllJson(item["children"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }
        }
        return tmpitem
    }
    function getxmselect(el,name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            autoRow: true,
            filterable: true,
            radio: true,
            initValue:[selectdata[0].code],//设置默认选中
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                expandedKeys: [ -3 ],
                strict: false,
            },
            height: '300px',
            data: data,
            on: function(data){
                if(data.isAdd){
                    return data.change.slice(0, 1)
                }
            },
        });
    }
    //json转tree
    function toTree(data) {
        let result = []
        if(!Array.isArray(data)) {
            return result
        }
        let map = {};
        data.forEach(item => {
            map[item.id] = item;
        });
        data.forEach(item => {
            let parent = map[item.pid];
            if(parent) {
                (parent.children || (parent.children = [])).push(item);
            } else {
                result.push(item);
            }
        });
        return result;
    }
});
